package com.study.io.nio.demo.buffer;

import java.nio.ByteBuffer;

/**
 * ByteBuffer demo
 * <p>
 * 直接在 JVM 堆上进行内存的分配， 本质上是 byte[] 数组的封装。
 * 因为 Non-Direct Buffer 在 JVM 堆中， 因此当进行操作系统底层 IO 操作中时， 会将此 buffer 的内存复制到中间临时缓冲区中. 因此 Non-Direct Buffer 的效率就较低。
 *
 * @author wuxj
 */
public class ByteBufferDemo {

    public static void main(String[] args) {
        //pos 0 lim 6 cap 6
        ByteBuffer buffer = ByteBuffer.allocate(6);
        //pos 6 lim 6 cap 6
        buffer.put("你哈".getBytes());

        //反转 lim = pos; pos = 0; mark = -1;
        buffer.flip();
        System.out.println(buffer.get());
        System.out.println(buffer.get());
        System.out.println(buffer.get());
        System.out.println(buffer.get());
        System.out.println(buffer.get());
        System.out.println(buffer.get());

        //反转 lim = pos; pos = 0; mark = -1;
        buffer.flip();
        byte[] b = new byte[6];
        buffer.get(b);
        System.out.println(new String(b));

        //wrap 这个缓冲区的数据会存放在byte数组中，bytes数组或buff缓冲区任何一方中数据的改动都会影响另一方
        b[0] = (byte) 1;
        b[1] = (byte) 2;
        b[2] = (byte) 3;
        b[3] = (byte) 4;
        b[4] = (byte) 5;
        b[5] = (byte) 6;
        buffer = ByteBuffer.wrap(b);
        b[5] = (byte) 0;
        System.out.println(buffer.get());
        System.out.println(buffer.get());
        System.out.println(buffer.get());
        System.out.println(buffer.get());
        System.out.println(buffer.get());
        System.out.println(buffer.get());

        //反转 lim = pos; pos = 0; mark = -1;
        buffer.flip();
        //标记初始位置
        buffer.mark();
        System.out.println(buffer.get());
        //回到mark地址
        buffer.reset();
        //清除数据
        buffer.clear();
    }
}
